package com.registration.controller;

import com.registration.Annotation.OperateLog;
import com.registration.bean.UserBean;
import com.registration.mapper.UserMapper;
import com.registration.util.JsonResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@RestController
@RequestMapping("/upload")
@CrossOrigin
public class UploadFileController {

    @Autowired
    private UserMapper userMapper;
    @PostMapping("/file")
    @OperateLog("上传文件")
    public JsonResponse uploadFile(Integer user_id, MultipartFile file) {
        JsonResponse jsonResponse = new JsonResponse();
        if(file != null){
            String fileName = file.getOriginalFilename();
            try {

                String path = "D:\\JAVA\\apache-tomcat-8.5.58\\webapps\\images";
                File dir=new File(path);

                if(!dir.exists()){dir.mkdirs();}

                File saveFile=new File(dir,fileName);
                file.transferTo(saveFile);
                String url = "http://192.168.116.9:8899/images/"+fileName;
                jsonResponse.setCode(0);
                jsonResponse.setData(url);
                UserBean userBean = new UserBean();
                userBean.setUser_id(user_id);
                userBean.setAvatar(url);
                userMapper.updateUser(userBean);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return jsonResponse;
    }

}
